package com.erf.client;

import com.erf.exception.NoConnectException;
import com.erf.message.SubmitRequest;
import com.erf.message.SubmitRequestResponse;
import com.erf.tools.SequenceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author zhangzy
 * @date 2022/7/9
 */
@RestController
public class SendDemoController {
    @Autowired
    RpcClient rpcClient;

    @RequestMapping("call")
    public String call() {
        SubmitRequest submitRequest = new SubmitRequest();
        submitRequest.setSequence(SequenceUtil.getSequenceId());
        submitRequest.setClassName("com.erf.tools.Test");
        submitRequest.setSpringInvokeName("test");
        submitRequest.setMethodName("call");
        submitRequest.setParamsTypes(new Class[]{String.class});
        submitRequest.setParamsValues(new Object[]{"hello world!"});
        try {
            return (String) Objects.requireNonNull(RpcClient.writeRandom("zhangzy", submitRequest)).getResult();
        } catch (NoConnectException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * todo 不知道是什么原因，json第一次解析自定义Exception时，产生bug报错,详情见codec
     */
    @RequestMapping("exception")
    @ResponseBody
    public Exception exception() {
        SubmitRequest submitRequest = new SubmitRequest();
        submitRequest.setSequence(SequenceUtil.getSequenceId());
        submitRequest.setClassName("com.erf.tools.Test");
        submitRequest.setSpringInvokeName("test");
        submitRequest.setMethodName("throwAnException");
        submitRequest.setParamsTypes(new Class[]{String.class});
        submitRequest.setParamsValues(new Object[]{"hello world!"});
        try {
            Exception e = (Exception) Objects.requireNonNull(RpcClient.writeRandom("zhangzy", submitRequest)).getResult();
            e.printStackTrace();
            return e;
        } catch (NoConnectException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
